package com.beijiteshop.shop.ui.order.fragment

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.beijiteshop.libcommon.base.adapter.showError
import com.beijiteshop.libcommon.base.adapter.showLoading
import com.beijiteshop.libcommon.base.adapter.showNetError
import com.beijiteshop.libcommon.ext.databinding.bindView
import com.beijiteshop.libcommon.ext.databinding.inflateBinding
import com.beijiteshop.libcommon.utils.EventUtil
import com.beijiteshop.shop.R
import com.beijiteshop.shop.app.PageIndex
import com.beijiteshop.shop.base.BaseContainerFragment
import com.beijiteshop.shop.databinding.FragmentOrderConfirmListBinding
import com.beijiteshop.shop.databinding.HeaderOrderConfirmListBinding
import com.beijiteshop.shop.model.api.request.AddCartOrderRequest
import com.beijiteshop.shop.model.api.request.ShopCartId
import com.beijiteshop.shop.model.api.response.AddressBean
import com.beijiteshop.shop.model.api.response.CartOrderConfirmBean
import com.beijiteshop.shop.model.api.response.Coupon
import com.beijiteshop.shop.model.entity.CheckBoxEntity
import com.beijiteshop.shop.model.event.EventKey
import com.beijiteshop.shop.ui.address.fragment.AddressFragment
import com.beijiteshop.shop.ui.order.adapter.OrderConfirmListAdapter
import com.beijiteshop.shop.ui.order.vm.OrderVM
import com.beijiteshop.shop.utils.twoDecimal
import org.koin.android.viewmodel.ext.android.viewModel

/**
 * @Author LiaoZhongKai
 * @Date 2021/3/22 16:51
 * @Description 购物车订单确认页面
 */
class OrderConfirmListFragment : BaseContainerFragment(R.layout.fragment_order_confirm_list) {

    companion object{
        const val CART_IDS = "cart_ids"

        fun newInstance(cartId: Array<String>): OrderConfirmListFragment{
            return OrderConfirmListFragment().apply {
                arguments = Bundle().apply {
                    putStringArray(CART_IDS,cartId)
                }
            }
        }
    }

    private val mBinding by bindView<FragmentOrderConfirmListBinding>()
    private lateinit var mHeaderBinding: HeaderOrderConfirmListBinding
    private val mOrderVM: OrderVM by viewModel()
    private var mCartIds: Array<String>? = null
    private var mAdapter = OrderConfirmListAdapter(mutableListOf())
    private var mOrderConfirmBean: CartOrderConfirmBean? = null
    private val mCouponSelectDialog: CouponSelectDialog by lazy {
        CouponSelectDialog()
    }
    //优惠券列表
    private var mCouponList: MutableList<CheckBoxEntity<Coupon>>? = null
    //当前选择的优惠券，如果有优惠券则默认第一个，没有默认null
    private var mSelectCoupon: Coupon? = null


    override fun initView(view: View) {
        mBinding.includeTitleBar.titleBarTitleTv.text = resources.getString(R.string.order_info_confirm)
        mHeaderBinding = inflateBinding(LayoutInflater.from(requireContext()))
        initRV()
    }

    override fun initData() {
        mCartIds = arguments?.getStringArray(CART_IDS)
    }

    override fun initEvent() {
        mBinding.includeTitleBar.titleBarBackIv.setOnClickListener {
            close()
        }

        mHeaderBinding.orderConfirmArrowIv.setOnClickListener {
            startActivity(PageIndex.ADDRESS,Bundle().apply {
                putBoolean(AddressFragment.BUNDLE_IS_SELECT,true)
            })
        }

        //优惠券
        mHeaderBinding.orderConfirmCouponNumTv.setOnClickListener {
            if (!mCouponList.isNullOrEmpty()){
                mCouponSelectDialog.show(childFragmentManager,mCouponList!!)
            }
        }


        //接收地址更改的事件
        EventUtil.observe<AddressBean?>(this, EventKey.ORDER_ADDRESS){ address ->
            address?.let {
                mHeaderBinding.address = it
                mOrderConfirmBean?.address = it
            }
        }

        //优惠券选择框
        mCouponSelectDialog.setOnSelectListener(object : CouponSelectDialog.IOnSelectListener{
            override fun onSelect(position: Int,coupon: Coupon) {
                setCouponDiscountPrice(coupon.couponValue)
                updateCouponItem(position)
                updateNeedPayPrice(coupon)
            }
        })
        //提交订单
        mBinding.orderConfirmSubmitBtn.setOnClickListener {
            commitOrder()
        }

        startObserve()
    }

    override fun onLazyLoad() {
        getCartOrderInfo()
    }

    private fun getCartOrderInfo(){
        if (!mCartIds.isNullOrEmpty()){
            mAdapter.showLoading()
            mOrderVM.getCartOrderInfo(mCartIds!!)
        }
    }

    private fun startObserve(){
        mOrderVM.apply {
            liveCartOrderInfo.observeKt {
                mOrderConfirmBean = it
                initHeaderInfo()
                setOrderPrice()
                mAdapter.setNewInstance(it?.goods)
            }

            liveError.observeKt {
                mAdapter.showError(it){
                    getCartOrderInfo()
                }
            }

            liveNetError.observeKt {
                mAdapter.showNetError(it){
                    getCartOrderInfo()
                }
            }

            //订单提交失败
            liveCommitOrderFailed.observeKt {
                hideLoading()
                showToastInCenter(it?:resources.getString(R.string.something_error))
            }

            //订单提交成功
            liveCommitOrder.observeKt {orderNum ->
                hideLoading()
                if (!orderNum.isNullOrEmpty()){
                    startActivity(PageIndex.ORDER_PAY,Bundle().apply {
                        putString(OrderPayFragment.BUNDLE_ORDER_NUMBER,orderNum)
                    })
                    //通知购物车刷新
                    EventUtil.post(EventKey.REFRESH_SHOP_CART)
                    close()
                }
            }
        }
    }

    private fun initHeaderInfo(){
        mOrderConfirmBean?.let {
            //默认地址
            if (it.address != null){
                mHeaderBinding.address = it.address
            }else{
                mHeaderBinding.orderConfirmAddressTv.text = resources.getString(R.string.please_select_address)
            }
            mHeaderBinding.product = it
            //优惠券数量、价格
            if (!it.coupon.isNullOrEmpty()){
                setCouponNum(it.coupon!!.size)
                setCouponDiscountPrice(it.coupon!![0].couponValue)
                setCouponList(it.coupon!!)
                updateNeedPayPrice(it.coupon!![0])
            }else{
                setCouponNum(0)
                setCouponDiscountPrice(0f)
                setNeedPay(it.amount)
            }
        }
    }

    private fun setOrderPrice(){
        mOrderConfirmBean?.let {
            mBinding.orderConfirmPriceTv.text = it.amount
        }
    }

    private fun initRV(){
        mAdapter.apply {
            addHeaderView(mHeaderBinding.root)
        }
        mBinding.orderConfirmListRv.apply {
            layoutManager = LinearLayoutManager(requireContext())
            adapter = mAdapter
        }
    }

    /**
     * 设置优惠券数量
     */
    private fun setCouponNum(num: Int){
        val strFormat = resources.getString(R.string.coupon_num)
        mHeaderBinding.orderConfirmCouponNumTv.text = String.format(strFormat,num)
    }

    /**
     * 设置选中的优惠券优惠价格
     */
    private fun setCouponDiscountPrice(value: Float){
        val strFormat = resources.getString(R.string.negative_price_format)
        mOrderConfirmBean?.discounts = value.toString()
        mHeaderBinding.orderConfirmCouponPriceTv.text = String.format(strFormat, value)
    }

    /**
     * 设置优惠券列表
     */
    private fun setCouponList(coupons: List<Coupon>){
        mCouponList = mutableListOf()
        coupons.forEachIndexed { index, coupon ->
            mCouponList!!.add(CheckBoxEntity(index == 0,coupon))
        }
    }

    /**
     * 更新某个优惠券
     */
    private fun updateCouponItem(position: Int){
        if (mCouponList!= null){
            mCouponList!!.forEachIndexed { index, checkBoxEntity ->
                checkBoxEntity.isSelected = index == position
            }
        }
    }

    /**
     * 选择优惠券后更新应付价格
     * @param coupon 优惠券
     */
    private fun updateNeedPayPrice(coupon: Coupon){
        mSelectCoupon = coupon
        mOrderConfirmBean?.let {
            Log.d("TAG","needPay:${it.amount.toFloat()} coupon:${coupon.couponValue} total:${it.amount.toFloat()-coupon.couponValue}")
            mBinding.orderConfirmPriceTv.text = (it.amount.toFloat() - coupon.couponValue).twoDecimal().toString()
            it.amount = (it.amount.toFloat() - coupon.couponValue).twoDecimal().toString()
        }
    }

    /**
     * 设置应付价格
     */
    private fun setNeedPay(price: String){
        mBinding.orderConfirmPriceTv.text = price
    }

    /**
     * 提交订单
     */
    private fun commitOrder(){
        mOrderConfirmBean?.let {

            if (it.address == null){
                showToastInCenter(resources.getString(R.string.please_select_address))
                return@let
            }

            val goods = mutableListOf<ShopCartId>()
            //每个商品价格
            it.goods.forEach {good ->
                if (!good.bus_ShopCartID.isNullOrEmpty()){
                    goods.add(ShopCartId(good.price.toFloat(),good.bus_ShopCartID!!))
                }
            }
            //备注
            val remark = mHeaderBinding.orderConfirmProductRemarksEt.text.toString()
            val request = AddCartOrderRequest(it.amount.toFloat(),
                it.address!!.bus_AddressID,
                mSelectCoupon?.bus_Coupon_UserID?:"",
                mSelectCoupon?.couponValue?:0f,
                it.discounts.toFloat(),
                it.goodsamount.toFloat(),
                it.postage.toFloat(),
                remark,
                goods)

            showLoading(resources.getString(R.string.committing))
            mOrderVM.addCartOrder(request)
        }
    }

}